package samsung.sds.survey.surveyStatistics.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import samsung.sds.survey.surveyStatistics.controller.UserAnswerStatusController;
import samsung.sds.survey.surveyStatistics.dao.UserAnswerStatusMapper;
import samsung.sds.survey.surveyStatistics.model.UserAnswerStatus;
import samsung.sds.survey.surveyStatistics.service.UserAnswerStatusService;
import samsung.sds.system.common.baseQuery.AbstractBaseService;
import samsung.sds.system.common.baseQuery.BaseMapper;
import samsung.sds.system.export.service.ExportService;
import samsung.sds.system.export.service.ExportServiceImpl;
import samsung.sds.system.utils.CommonTools;
/**
 * @author  hulongtao 
 * @createDate 2016/02/18
 * */
@Service
public class UserAnswerStatusServiceImpl extends AbstractBaseService<UserAnswerStatus> implements UserAnswerStatusService{
	
	@Autowired
	private UserAnswerStatusMapper userAnswerStatusMapper;
	
	@Autowired
	private ExportService exportServiceImpl;
	
	private static final Logger log = Logger
			.getLogger(UserAnswerStatusController.class);

	/**
	 * 导出问卷调查明细数据,当前查询条件下全部数据查询
	 * 
	 * @param userAnswerStatus
	 * */
	@Override
	public List<UserAnswerStatus> exportList(UserAnswerStatus userAnswerStatus) {
		List<UserAnswerStatus> queryExportList = new ArrayList<UserAnswerStatus>();
		//对sql中查询进行转义字符
		userAnswerStatus.setUserName(CommonTools.escapeSQLParam(userAnswerStatus.getUserName()+""));
		queryExportList = this.userAnswerStatusMapper
				.selectTF_F_SURVEY(userAnswerStatus);
		for(int i=0;i<queryExportList.size();i++){
			if(queryExportList.get(i).getStatus().equals("1")){
				queryExportList.get(i).setStatus("已投票");
			}else{
				queryExportList.get(i).setStatus("未投票");
			}
		};
		return queryExportList;
	}

	/**
	 * 导出Excel方法
	 * 
	 * @param userAnswerStatus
	 * @throws Exception 
	 * */
	@Override
	public void processVotedUserExport(HttpServletRequest request,
			HttpServletResponse response, UserAnswerStatus userAnswerStatus) throws Exception {
		String fileName = null;
		OutputStream os = null;
		FileInputStream fis = null;
		log.info("==== >>>> export test here");
		try {
			UserAnswerStatus userAnswerStatusById = this
					.getDetailInfo(userAnswerStatus);
			String[] strDetail = {
					userAnswerStatusById.getSurveyName(),
					userAnswerStatusById.getLastModifyTime() == null ? ""
							: userAnswerStatusById.getLastModifyTime()
									.toString(),
					userAnswerStatusById.getAskForCounts() == null ? ""
							: userAnswerStatusById.getAskForCounts().toString(),
					userAnswerStatusById.getCounts()+"",
					userAnswerStatusById.getCreateTime() == null ? ""
							: userAnswerStatusById.getCreateTime().toString() };
			fileName = exportServiceImpl.createExcelForUserAnswerStatus(
					this.exportList(userAnswerStatus), strDetail);
			os = response.getOutputStream();
			long l = System.currentTimeMillis();
			response.setHeader("content-disposition", "attachment;filename="+ExportServiceImpl.toUtf8String(strDetail[0]+"_"+l,request));//修改导出的文件名
			response.setContentType("application/vnd.ms-excel");// 此项内容随文件类型而异
			byte temp[] = new byte[1000];
			fis = new FileInputStream(fileName);
			int n = 0;
			while ((n = fis.read(temp)) != -1) {
				os.write(temp, 0, n);
			}
		} catch (Exception e) {
			log.error("error occured when export voted user data");
			e.printStackTrace();
			throw e;
		} finally {
			if (os != null)
				try {
					os.close();
					if (fis != null)
						fis.close();
					if (new File(fileName).exists()) {
						new File(fileName).delete();
					}
				} catch (IOException e) {
					e.printStackTrace();
					throw e;
				}
		}
	}

	/**
	 * 获得问卷调查统计分析表头汇总信息方法
	 * 
	 * @param userAnswerStatus
	 * */
	@Override
	public UserAnswerStatus getDetailInfo(UserAnswerStatus userAnswerStatus) {
		UserAnswerStatus sur = new UserAnswerStatus();
		sur = this.userAnswerStatusMapper.selectTF_F_SURVEY_RESULT(userAnswerStatus);
		return sur;
	}

	/**
	 * 画饼图时，后台取数据，数据包含<投票邀请人数，已投票人数，未投票人数>
	 * 
	 * @param surveyId
	 * */
	@Override
	public Map<String, Integer> getPieInfo(String surveyId) {
		UserAnswerStatus sur = new UserAnswerStatus();
		sur.setSurveyId(new String(surveyId));
		List<UserAnswerStatus> list = this.userAnswerStatusMapper
				.selectTF_F_SURVEY(sur);
		Map<String, Integer> map = new HashMap<String, Integer>();
		int votedCounts = 0;
		for (UserAnswerStatus userAnswerStatus : list) {
			if (userAnswerStatus.getStatus().equals("1"))
				votedCounts++;
		}
		int noVotedCounts = list.size() - votedCounts;
		map.put("inviteVoteCounts", list.size());
		map.put("notVoteCounts", noVotedCounts);
		map.put("votedCounts", votedCounts);
		return map;
	}

	@Override
	protected BaseMapper<UserAnswerStatus> getMapper() {
		return userAnswerStatusMapper;
	}

}
